﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HRM.Data.Database;
using HRM.Shared.Interfaces;

namespace HRM.Data.Repository
{
    public abstract class BaseRepository<T>: IRepository<T>
    {
        protected HRMClientEntries _database;

        protected BaseRepository()
        {
            _database = new HRMClientEntries();
        }

        public abstract IEnumerable<T> GetList();
        public abstract T GetById(long id);
        public abstract void Create(T entity);
        public abstract void Update(T entity);
        public abstract void Delete(T entity);

        public void SaveChanges()
        {
            try
            {
                _database.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                var output = "";
                foreach (var eve in e.EntityValidationErrors)
                {
                    output += "\n" + (string.Format(
                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    output = eve.ValidationErrors.Aggregate(output, (current, ve) => current + ("\n" + (string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage))));
                }

                throw new Exception(output);
            }
        }
    }
}
